package com.myapp.db.conn;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.myapp.data.global.Instances;

public class ConnectionFactory {

	// 日志
	private Logger log = Logger.getLogger(ConnectionFactory.class);

	private static ConnectionFactory connectionFactory = null;

	private ComboPooledDataSource dataSource = null;

	public static ConnectionFactory getInstance() {
		if (connectionFactory == null) {
			connectionFactory = new ConnectionFactory();
		}
		return connectionFactory;
	}

	private ConnectionFactory() {
		try {
			dataSource = this.getDataSource(Instances.getAppConfigBean()
					.getCurrentPath()
					+ Instances.getAppConfigBean().getPoolConfig());
		} catch (Exception e) {
			log.error("Build Connection Pool Failure", e);
			System.exit(0);
		}
	}

	private ComboPooledDataSource getDataSource(String configFile)
			throws Exception {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		// 设置链接参数
		Properties prop = new Properties();
		InputStream is = null;
		Reader re = null;
		try {
			is = new FileInputStream(configFile);
			re = new InputStreamReader(is, "UTF-8");
			prop.load(re);
			// 初始化bean
			dataSource.setDriverClass(prop.getProperty("DriverClass"));
			dataSource.setJdbcUrl(prop.getProperty("JdbcUrl"));
			dataSource.setUser(prop.getProperty("User"));
			dataSource.setPassword(prop.getProperty("Password"));
			dataSource.setInitialPoolSize(Integer.parseInt(prop
					.getProperty("InitialPoolSize")));
			dataSource.setMaxPoolSize(Integer.parseInt(prop
					.getProperty("MaxPoolSize")));
			dataSource.setMinPoolSize(Integer.parseInt(prop
					.getProperty("MinPoolSize")));
			dataSource.setAcquireIncrement(Integer.parseInt(prop
					.getProperty("AcquireIncrement")));
			dataSource.setAutoCommitOnClose(Boolean.getBoolean(prop
					.getProperty("AutoCommitOnClose")));
			return dataSource;
		} finally {
			try {
				if (re != null) {
					re.close();
					re = null;
				}
			} catch (Exception e) {
			}

			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 获取数据库操作对象的session
	 * 
	 * @return Connection
	 * 
	 * @throws SQLException
	 */
	public Connection getDBConnection() throws SQLException {
		if (this.dataSource != null) {
			return this.dataSource.getConnection();
		} else {
			throw new IllegalArgumentException("DataSource is null");
		}
	}

}
